package com.mjk.common.web.getway.restful.interceptor.type.commons.impl;


import com.mjk.common.base.error.BeeError;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.base.work.annotation.BeeApi;
import com.mjk.common.base.work.annotation.BeeWork;
import com.mjk.common.tools.gson.GsonUtils;
import com.mjk.common.tools.interceptor.InterceptorChain;
import com.mjk.common.tools.springextend.BeeApplicationListener;
import com.mjk.common.tools.xml.XmlUtils;
import com.mjk.common.util.AopTargetUtils;
import com.mjk.common.util.MapUtils;
import com.mjk.common.util.ReflectionUtils;
import com.mjk.common.web.getway.constns.GetwayConsts;
import com.mjk.common.web.getway.restful.interceptor.GetWayInterceptorReq;
import com.mjk.common.web.getway.restful.interceptor.annotation.BeeGetWayInterceptor;
import com.mjk.common.web.getway.restful.interceptor.type.GetWayInterceptor;
import com.mjk.common.web.getway.restful.interceptor.type.GetWayInterceptorType;
import com.mjk.common.web.getway.transfer.GetwayTransfer;
import com.mjk.common.web.getway.transfer.http.HttpGetWayprotocol;
import com.mjk.common.web.getway.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextRefreshedEvent;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;

/**
 * 自定义返回结果
 * 用于返回 结果非标准的beeresponse 结果
 * 此处 会和 ApiModel 中的 returnType 有冲突 所以 添加了beeapi 注解的接口 有冲突，
 * 如果在此处定义了ApiModel就不会执行此处
 * @author msi
 *
 */
@BeeGetWayInterceptor(value = 3, interceptorType = {GetWayInterceptorType.ALL})
public class GetWayCustomResponseInterceptor implements GetWayInterceptor, BeeApplicationListener {
	@Autowired
	private GetwayTransfer transfer;

	@Override
	public BeeResponse interceptor(GetWayInterceptorReq request,
								   InterceptorChain<GetWayInterceptorReq, BeeResponse> next) {
		String work = MapUtils.getString(request.getRestfulParams(), GetwayConsts.INSTANCE);
		String method = MapUtils.getString(request.getParams(), GetwayConsts.METHOD);
		BeeResponse response = next.proceed(request);
		if (BeeError.BEE_SUC.getCode().equals(response.getCode()) && transfer instanceof HttpGetWayprotocol wayprotocol) {
			Method m = ReflectionUtils.getMethodByName(wayprotocol.getWork(work).getClass(), method);
			BeeApi api = m.getAnnotation(BeeApi.class);
			if (null != api && !api.type().equals(BeeApi.ResponseType.NORMAL)) {
				switch (api.type()) {
					case JSON:
						ResponseUtils.returnGetWay(request.getResponse(), GsonUtils.bean2Json(response.getData()));
						break;
					case XML:
						ResponseUtils.returnGetWay(request.getResponse(), XmlUtils.beanToXml(response.getData()));
						break;
					case CUSTOM:
						ResponseUtils.returnGetWay(request.getResponse(), response.getData());
						break;
				}
			}
		}
		return response;
	}


}
